package com.arpa.oms.service.impl;

import cn.hutool.core.collection.IterUtil;
import com.arpa.core.utils.misc.IdGenerator;
import com.arpa.oms.domain.entity.SaleItem;
import com.arpa.oms.domain.entity.SalePacks;
import com.arpa.oms.domain.enums.SalePacksOrderStatusEnum;
import com.arpa.oms.mapper.SalePacksMapper;
import com.arpa.oms.service.ISaleItemService;
import com.arpa.oms.service.ISalePacksService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * OMS销售单拆单子表 服务实现类
 * </p>
 *
 * @author SPB
 * @since 2021-10-25
 */
@Service
@Log4j2(topic = "business")
public class SalePacksServiceImpl extends ServiceImpl<SalePacksMapper, SalePacks> implements ISalePacksService {

    @Autowired
    private ISaleItemService iSaleItemService;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void create(List<SalePacks> resultList) {
        List<SalePacks> list = new ArrayList<>();
        List<SaleItem> saleItems = new ArrayList<>();
        int i = 1;
        for (SalePacks salePacks : resultList) {
            salePacks.setMasterSaleCode(salePacks.getCode());
            salePacks.setCode(salePacks.getCode() + "-" + i);
            salePacks.setOrderStatus(SalePacksOrderStatusEnum.NOSEND.getValue());
            List<SaleItem> items = salePacks.getSaleItemList();
            for (SaleItem item : items) {
                item.setSaleCode(salePacks.getCode());
                String uuid = IdGenerator.uuid2();
                System.out.println(uuid);
                item.setCode(uuid);
                saleItems.add(item);
            }
            list.add(salePacks);
            i++;
        }

        if (IterUtil.isNotEmpty(list)) {
            saveBatch(list);
        }

        if (IterUtil.isNotEmpty(saleItems)) {
            iSaleItemService.saveBatch(saleItems);
        }
    }
}
